package ecnu.ecgbackend.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import ecnu.ecgbackend.config.security.exception.CustomerAuthenticationException;
import ecnu.ecgbackend.utils.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//        System.out.println("request: "+request.toString());
//        System.out.println("response: "+response.toString());
//        response.setContentType("application/json;charset=UTF-8");
//        ServletOutputStream outputStream= response.getOutputStream();
//        String result= JSON.toJSONString(Result.error().code(600).message("用户或密码错误"), SerializerFeature.DisableCircularReferenceDetect);
//        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
//        outputStream.flush();
//        outputStream.close();
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream=response.getOutputStream();
        String message=null;
        int code=500;
        if(authException instanceof AccountExpiredException){
            message="账户过期，登录失败！";
        }else if(authException instanceof BadCredentialsException){
            message="用户名或密码错误，登录失败！";
        }else if(authException instanceof DisabledException){
            message="账户被禁用，登录失败！";
        }else if(authException instanceof LockedException){
            message="账户被锁，登录失败！";
        }else if(authException instanceof InternalAuthenticationServiceException){
            message="账户不存在，登录失败！";
        }else if(authException instanceof CustomerAuthenticationException){
            message=authException.getMessage();
            code=600;
        }else {
            message="登录失败！";
        }
        String result= JSON.toJSONString(Result.error().code(code).message(message));
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
